'Copyright (c) 2008, Jonathan Allen
Imports ClrExtensions
Imports WrapNetflix
Imports ClrExtensions.Net.Rest


Public Class ResourceLink
    Inherits NetflixResource
    Private m_Loaded As Boolean

    Public ReadOnly Property Loaded() As Boolean
        Get
            Return m_Loaded
        End Get
    End Property

    Public Sub New(ByVal connection As NetflixConnection, ByVal source As XElement)
        MyBase.New(connection, source)
    End Sub

    Public Overrides ReadOnly Property Id() As String
        Get
            Return Source.@href
        End Get
    End Property

    Public Overrides ReadOnly Property Title() As String
        Get
            Return Source.@title
        End Get
    End Property

    Public Function GetChildLinks() As ResourceLinkCollection
        Dim temp As New List(Of ResourceLink)
        For Each node In Source...<link>
            temp.Add(New ResourceLink(Connection, node))
        Next
        Return New ResourceLinkCollection(temp)
    End Function



    Public Function GetCatalogTitles(ByVal load As Boolean) As CatalogTitleCollection
        If load Then Me.Load()

        Dim temp As New List(Of CatalogTitle)
        For Each node In Source...<catalog_title>
            temp.Add(CatalogTitle.ParseEntry(Connection, node))
        Next
        Return New CatalogTitleCollection(temp)
    End Function

    ''' <summary>
    ''' Loads the resource in-place
    ''' </summary>
    ''' <remarks></remarks>
    Public Sub Load()
        If Not m_Loaded Then
            Me.Source = FetchXml()
            m_Loaded = True
        End If
    End Sub

    ''' <summary>
    ''' Loads the linked resource in-place and then returns a matching CatalogTitle
    ''' </summary>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Public Function ParseAsCataglogTitle() As CatalogTitle
        Load()
        Return CatalogTitle.ParseEntry(Connection, Me.Source)
    End Function

    ''' <summary>
    ''' Returns the linked resource as XML
    ''' </summary>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Public Function FetchXml() As XElement
        Return Connection.RequestXmlResource(New RestCall(RestVerb.Get, Id))
    End Function

    ''' <summary>
    ''' Returns the linked resource as a raw string
    ''' </summary>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Public Function Fetch() As String
        Return Connection.RequestResource(New RestCall(RestVerb.Get, Id))
    End Function

End Class
